#!/bin/bash

# LimeReader & LoimReader 通用部署脚本
# 支持双客户端部署，默认 LimeReader
# 作者: Wang Zhen
# 版本: 2.0.0

set -e  # 遇到错误立即退出

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 配置变量
DEFAULT_CLIENT="LimeReader"
SUPPORTED_CLIENTS=("LimeReader" "LoimReader")
OSS_BUCKET="limereader-releases"
OSS_REGION="oss-cn-hangzhou"
OSS_BASE_URL="https://limereader-releases.oss-cn-hangzhou.aliyuncs.com"

# 显示脚本横幅
echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE}    LimeReader & LoimReader 部署脚本${NC}"
echo -e "${BLUE}           版本 2.0.0${NC}"
echo -e "${BLUE}========================================${NC}"
echo ""

# 检查Python版本
echo -e "${GREEN}📋 检查Python环境...${NC}"
if ! command -v python3 &> /dev/null; then
    echo -e "${RED}❌ 错误: 未找到Python3，请先安装Python3${NC}"
    exit 1
fi

PYTHON_VERSION=$(python3 -c "import sys; print(f'{sys.version_info.major}.{sys.version_info.minor}')")
echo -e "${GREEN}✅ Python版本: $PYTHON_VERSION${NC}"

if [[ $(echo "$PYTHON_VERSION >= 3.7" | bc -l) -eq 0 ]]; then
    echo -e "${RED}❌ 错误: Python版本需要3.7或更高${NC}"
    exit 1
fi

# 选择客户端
echo -e "${YELLOW}🔧 选择要部署的客户端:${NC}"
echo "1) LimeReader (默认)"
echo "2) LoimReader"
echo ""

read -p "请输入选择 [1-2] (默认: 1): " client_choice

case $client_choice in
    2)
        CLIENT_NAME="LoimReader"
        CLIENT_DIR="loimreader"
        CLIENT_PREFIX="LoimReader"
        ;;
    *)
        CLIENT_NAME="LimeReader"
        CLIENT_DIR="limereader"
        CLIENT_PREFIX="LimeReader"
        ;;
esac

echo -e "${GREEN}✅ 已选择客户端: $CLIENT_NAME${NC}"
echo ""

# 选择操作模式
echo -e "${YELLOW}🔧 选择部署模式:${NC}"
echo "1) 完整部署 (包含OSS上传)"
echo "2) 仅本地测试"
echo "3) 仅上传到OSS"
echo ""

read -p "请输入选择 [1-3] (默认: 1): " mode_choice

case $mode_choice in
    2)
        DEPLOY_MODE="local"
        ;;
    3)
        DEPLOY_MODE="oss_only"
        ;;
    *)
        DEPLOY_MODE="full"
        ;;
esac

echo -e "${GREEN}✅ 部署模式: $DEPLOY_MODE${NC}"
echo ""

# 收集版本信息
echo -e "${YELLOW}📝 输入版本信息:${NC}"
read -p "版本号 (如: 2.7.1): " VERSION
if [ -z "$VERSION" ]; then
    echo -e "${RED}❌ 错误: 版本号不能为空${NC}"
    exit 1
fi

read -p "发布日期 (默认: $(date -u +%Y-%m-%dT%H:%M:%SZ)): " RELEASE_DATE
RELEASE_DATE=${RELEASE_DATE:-$(date -u +%Y-%m-%dT%H:%M:%SZ)}

read -p "更新日志: " RELEASE_NOTES
if [ -z "$RELEASE_NOTES" ]; then
    RELEASE_NOTES="$CLIENT_NAME 版本 $VERSION 更新发布"
fi

echo ""
echo -e "${GREEN}📋 版本信息确认:${NC}"
echo "  客户端: $CLIENT_NAME"
echo "  版本号: $VERSION"
echo "  发布日期: $RELEASE_DATE"
echo "  更新日志: $RELEASE_NOTES"
echo ""

read -p "确认信息正确? [Y/n]: " confirm
if [[ $confirm == "n" || $confirm == "N" ]]; then
    echo -e "${YELLOW}⚠️  部署已取消${NC}"
    exit 0
fi

# 创建虚拟环境
if [ "$DEPLOY_MODE" != "oss_only" ]; then
    echo -e "${GREEN}🐍 准备Python环境...${NC}"
    if [ ! -d "venv" ]; then
        python3 -m venv venv
        echo -e "${GREEN}✅ 虚拟环境创建完成${NC}"
    else
        echo -e "${GREEN}✅ 虚拟环境已存在${NC}"
    fi

    # 激活虚拟环境
    echo -e "${GREEN}🔄 激活虚拟环境...${NC}"
    source venv/bin/activate

    # 升级pip
    echo -e "${GREEN}⬆️  升级pip...${NC}"
    pip install --upgrade pip

    # 安装依赖
    echo -e "${GREEN}📦 安装依赖...${NC}"
    if [ -f "requirements.txt" ]; then
        pip install -r requirements.txt
    else
        # 安装基础依赖
        pip install requests pyyaml cryptography
    fi
fi

# 创建目录结构
echo -e "${GREEN}📁 创建目录结构...${NC}"
mkdir -p "dist/$CLIENT_NAME/windows"
mkdir -p "dist/$CLIENT_NAME/macos"
mkdir -p "dist/$CLIENT_NAME/linux"
mkdir -p "uploads/$CLIENT_NAME"
mkdir -p "logs"
mkdir -p "backups"

echo -e "${GREEN}✅ 目录结构创建完成${NC}"

# 生成版本信息文件模板
echo -e "${GREEN}📄 生成版本信息文件...${NC}"
VERSION_FILE="uploads/$CLIENT_NAME/version.json"

cat > "$VERSION_FILE" << EOF
{
  "latestVersion": "$VERSION",
  "releaseDate": "$RELEASE_DATE",
  "releaseNotes": "$RELEASE_NOTES",
  "forceUpdate": false,
  "packages": {
    "windows": {
      "url": "${CLIENT_PREFIX}_v${VERSION}_Windows.zip",
      "size": "待填写",
      "hash": "待填写",
      "downloadUrl": "${OSS_BASE_URL}/updates/${CLIENT_DIR}/${CLIENT_PREFIX}_v${VERSION}_Windows.zip",
      "minSystemVersion": "Windows 10 或更高版本"
    },
    "macos": {
      "url": "${CLIENT_PREFIX}_v${VERSION}_macOS.dmg",
      "size": "待填写",
      "hash": "待填写",
      "downloadUrl": "${OSS_BASE_URL}/updates/${CLIENT_DIR}/${CLIENT_PREFIX}_v${VERSION}_macOS.dmg",
      "minSystemVersion": "macOS 10.15 或更高版本"
    },
    "linux": {
      "url": "${CLIENT_PREFIX}_v${VERSION}_Linux.tar.gz",
      "size": "待填写",
      "hash": "待填写",
      "downloadUrl": "${OSS_BASE_URL}/updates/${CLIENT_DIR}/${CLIENT_PREFIX}_v${VERSION}_Linux.tar.gz",
      "minSystemVersion": "Linux Kernel 4.15 或更高版本"
    }
  }
}
EOF

echo -e "${GREEN}✅ 版本信息文件已生成: $VERSION_FILE${NC}"

# 生成构建脚本
echo -e "${GREEN}🔨 生成构建脚本...${NC}"
BUILD_SCRIPT="build_${CLIENT_DIR}.sh"

cat > "$BUILD_SCRIPT" << 'EOF'
#!/bin/bash

# 自动化构建脚本
set -e

CLIENT_NAME="%CLIENT_NAME%"
CLIENT_PREFIX="%CLIENT_PREFIX%"
VERSION="%VERSION%"
BUILD_DIR="dist/$CLIENT_NAME"

echo "开始构建 $CLIENT_NAME v$VERSION"

# 构建Windows包
if [ -d "$BUILD_DIR/windows" ]; then
    echo "构建Windows包..."
    cd "$BUILD_DIR/windows"
    7z a -tzip "${CLIENT_PREFIX}_v${VERSION}_Windows.zip" *
    mv "${CLIENT_PREFIX}_v${VERSION}_Windows.zip" ../../uploads/$CLIENT_NAME/
    cd ../../..
    echo "Windows包构建完成"
fi

# 构建macOS包
if [ -d "$BUILD_DIR/macos" ]; then
    echo "构建macOS包..."
    if [ -f "$BUILD_DIR/macos/$CLIENT_NAME.app" ]; then
        hdiutil create -volname "$CLIENT_NAME" -srcfolder "$BUILD_DIR/macos/" -ov -format UDZO "${CLIENT_PREFIX}_v${VERSION}_macOS.dmg"
        mv "${CLIENT_PREFIX}_v${VERSION}_macOS.dmg" uploads/$CLIENT_NAME/
        echo "macOS包构建完成"
    fi
fi

# 构建Linux包
if [ -d "$BUILD_DIR/linux" ]; then
    echo "构建Linux包..."
    cd "$BUILD_DIR/linux"
    tar -czf "${CLIENT_PREFIX}_v${VERSION}_Linux.tar.gz" *
    mv "${CLIENT_PREFIX}_v${VERSION}_Linux.tar.gz" ../../uploads/$CLIENT_NAME/
    cd ../../..
    echo "Linux包构建完成"
fi

# 计算文件哈希和大小
echo "计算文件哈希和大小..."
cd "uploads/$CLIENT_NAME"

for file in ${CLIENT_PREFIX}_v${VERSION}_*; do
    if [ -f "$file" ]; then
        size=$(ls -lh "$file" | awk '{print $5}')
        hash=$(md5sum "$file" | awk '{print $1}')
        echo "文件: $file"
        echo "大小: $size"
        echo "哈希: $hash"
        echo ""
    fi
done

cd ../..
echo "构建完成！"
EOF

# 替换模板变量
sed -i.bak "s/%CLIENT_NAME%/$CLIENT_NAME/g" "$BUILD_SCRIPT"
sed -i.bak "s/%CLIENT_PREFIX%/$CLIENT_PREFIX/g" "$BUILD_SCRIPT"
sed -i.bak "s/%VERSION%/$VERSION/g" "$BUILD_SCRIPT"
rm "$BUILD_SCRIPT.bak"

chmod +x "$BUILD_SCRIPT"

echo -e "${GREEN}✅ 构建脚本已生成: $BUILD_SCRIPT${NC}"

# 生成哈希计算脚本
echo -e "${GREEN}🔐 生成哈希计算脚本...${NC}"
HASH_SCRIPT="calculate_hashes_${CLIENT_DIR}.sh"

cat > "$HASH_SCRIPT" << 'EOF'
#!/bin/bash

# 文件哈希和大小计算脚本
CLIENT_NAME="%CLIENT_NAME%"
CLIENT_PREFIX="%CLIENT_PREFIX%"
VERSION="%VERSION%"

echo "计算 $CLIENT_NAME v$VERSION 文件哈希和大小"
echo ""

cd "uploads/$CLIENT_NAME"

# 初始化JSON变量
windows_size=""
windows_hash=""
macos_size=""
macos_hash=""
linux_size=""
linux_hash=""

# 检查并计算各平台文件
for file in ${CLIENT_PREFIX}_v${VERSION}_*; do
    if [ -f "$file" ]; then
        size=$(ls -lh "$file" | awk '{print $5}')
        hash=$(md5sum "$file" | awk '{print $1}')

        case $file in
            *Windows*)
                windows_size="$size"
                windows_hash="$hash"
                ;;
            *macOS*)
                macos_size="$size"
                macos_hash="$hash"
                ;;
            *Linux*)
                linux_size="$size"
                linux_hash="$hash"
                ;;
        esac

        echo "文件: $file"
        echo "大小: $size"
        echo "哈希: $hash"
        echo ""
    fi
done

# 更新版本文件
echo "更新版本信息文件..."
python3 << PYTHON_SCRIPT
import json
import sys

# 读取现有版本文件
with open('version.json', 'r', encoding='utf-8') as f:
    version_data = json.load(f)

# 更新包信息
if '$windows_size':
    version_data['packages']['windows']['size'] = '$windows_size'
    version_data['packages']['windows']['hash'] = '$windows_hash'

if '$macos_size':
    version_data['packages']['macos']['size'] = '$macos_size'
    version_data['packages']['macos']['hash'] = '$macos_hash'

if '$linux_size':
    version_data['packages']['linux']['size'] = '$linux_size'
    version_data['packages']['linux']['hash'] = '$linux_hash'

# 保存更新后的版本文件
with open('version.json', 'w', encoding='utf-8') as f:
    json.dump(version_data, f, indent=2, ensure_ascii=False)

print("版本信息文件已更新")
PYTHON_SCRIPT

cd ../..
echo "哈希计算完成！"
EOF

# 替换模板变量
sed -i.bak "s/%CLIENT_NAME%/$CLIENT_NAME/g" "$HASH_SCRIPT"
sed -i.bak "s/%CLIENT_PREFIX%/$CLIENT_PREFIX/g" "$HASH_SCRIPT"
sed -i.bak "s/%VERSION%/$VERSION/g" "$HASH_SCRIPT"
rm "$HASH_SCRIPT.bak"

chmod +x "$HASH_SCRIPT"

echo -e "${GREEN}✅ 哈希计算脚本已生成: $HASH_SCRIPT${NC}"

# 生成OSS上传脚本
echo -e "${GREEN}☁️  生成OSS上传脚本...${NC}"
OSS_SCRIPT="upload_to_oss_${CLIENT_DIR}.sh"

cat > "$OSS_SCRIPT" << 'EOF'
#!/bin/bash

# OSS上传脚本
CLIENT_NAME="%CLIENT_NAME%"
CLIENT_DIR="%CLIENT_DIR%"
VERSION="%VERSION%"

echo "开始上传 $CLIENT_NAME v$VERSION 到OSS"

# 检查ossutil是否已安装
if ! command -v ossutil64 &> /dev/null; then
    echo "错误: 未找到ossutil64，请先安装阿里云OSS工具"
    echo "下载地址: https://help.aliyun.com/zh/oss/developer-tools/ossutil"
    exit 1
fi

# 检查是否已配置
if ! ossutil64 config list &> /dev/null; then
    echo "错误: ossutil未配置，请先运行: ossutil64 config"
    exit 1
fi

OSS_BUCKET="limereader-releases"
OSS_PATH="updates/$CLIENT_DIR/"

echo "上传文件到OSS..."

# 上传更新包
cd "uploads/$CLIENT_NAME"

for file in *_v${VERSION}_*; do
    if [ -f "$file" ]; then
        echo "上传: $file"
        ossutil64 cp "$file" "oss://$OSS_BUCKET/$OSS_PATH$file"
        echo "✅ $file 上传完成"
    fi
done

# 上传版本文件（最后一步）
echo "上传版本信息文件..."
ossutil64 cp "version.json" "oss://$OSS_BUCKET/$OSS_PATH/version.json"
echo "✅ version.json 上传完成"

cd ../..
echo "OSS上传完成！"

# 验证文件可访问性
echo "验证文件可访问性..."
BASE_URL="https://limereader-releases.oss-cn-hangzhou.aliyuncs.com"

# 检查版本文件
if curl -s "$BASE_URL/$OSS_PATH/version.json" > /dev/null; then
    echo "✅ 版本文件可访问: $BASE_URL/$OSS_PATH/version.json"
else
    echo "❌ 版本文件不可访问"
fi

# 检查更新包
for file in *_v${VERSION}_*; do
    if [ -f "$file" ]; then
        if curl -s "$BASE_URL/$OSS_PATH$file" > /dev/null; then
            echo "✅ 更新包可访问: $BASE_URL/$OSS_PATH$file"
        else
            echo "❌ 更新包不可访问: $file"
        fi
    fi
done

echo "验证完成！"
EOF

# 替换模板变量
sed -i.bak "s/%CLIENT_NAME%/$CLIENT_NAME/g" "$OSS_SCRIPT"
sed -i.bak "s/%CLIENT_DIR%/$CLIENT_DIR/g" "$OSS_SCRIPT"
sed -i.bak "s/%VERSION%/$VERSION/g" "$OSS_SCRIPT"
rm "$OSS_SCRIPT.bak"

chmod +x "$OSS_SCRIPT"

echo -e "${GREEN}✅ OSS上传脚本已生成: $OSS_SCRIPT${NC}"

# 设置权限
echo -e "${GREEN}🔐 设置文件权限...${NC}"
chmod +x *.sh
chmod 755 uploads
chmod 755 logs
chmod 755 backups

echo -e "${GREEN}✅ 权限设置完成${NC}"

# 本地测试
if [ "$DEPLOY_MODE" != "oss_only" ]; then
    echo -e "${GREEN}🧪 执行本地测试...${NC}"

    # 激活虚拟环境
    if [ -d "venv" ]; then
        source venv/bin/activate
    fi

    # 测试版本文件格式
    echo "测试版本文件格式..."
    if python3 -c "import json; json.load(open('$VERSION_FILE'))"; then
        echo -e "${GREEN}✅ 版本文件格式正确${NC}"
    else
        echo -e "${RED}❌ 版本文件格式错误${NC}"
        exit 1
    fi

    echo -e "${GREEN}✅ 本地测试通过${NC}"
fi

# OSS上传（完整部署模式）
if [ "$DEPLOY_MODE" == "full" ]; then
    echo -e "${GREEN}☁️  开始OSS上传...${NC}"

    if [ -f "$OSS_SCRIPT" ]; then
        if ./"$OSS_SCRIPT"; then
            echo -e "${GREEN}✅ OSS上传成功${NC}"
        else
            echo -e "${RED}❌ OSS上传失败${NC}"
            exit 1
        fi
    else
        echo -e "${YELLOW}⚠️  OSS上传脚本不存在，跳过上传${NC}"
    fi
fi

# 生成部署报告
echo -e "${GREEN}📊 生成部署报告...${NC}"
REPORT_FILE="deployment_report_${CLIENT_DIR}_v${VERSION}_$(date +%Y%m%d_%H%M%S).json"

cat > "$REPORT_FILE" << EOF
{
  "deploymentInfo": {
    "clientName": "$CLIENT_NAME",
    "clientDir": "$CLIENT_DIR",
    "clientPrefix": "$CLIENT_PREFIX",
    "version": "$VERSION",
    "releaseDate": "$RELEASE_DATE",
    "deployMode": "$DEPLOY_MODE",
    "deployTime": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",
    "deployScript": "universal_deploy.sh",
    "scriptVersion": "2.0.0"
  },
  "generatedFiles": [
    "$VERSION_FILE",
    "$BUILD_SCRIPT",
    "$HASH_SCRIPT",
    "$OSS_SCRIPT",
    "$REPORT_FILE"
  ],
  "nextSteps": [
    "1. 将构建好的应用文件放入 dist/$CLIENT_NAME/ 对应平台目录",
    "2. 运行构建脚本: ./$BUILD_SCRIPT",
    "3. 运行哈希计算: ./$HASH_SCRIPT",
    "4. 上传到OSS: ./$OSS_SCRIPT",
    "5. 测试版本检查API"
  ],
  "apiTestCommands": {
    "versionCheck": "curl -X POST https://your-domain.com/api/client/version/check -H 'Content-Type: application/json' -d '{\"clientName\":\"$CLIENT_NAME\",\"currentVersion\":\"$VERSION\",\"platform\":\"windows\"}'",
    "versionFile": "curl $OSS_BASE_URL/updates/$CLIENT_DIR/version.json"
  }
}
EOF

echo -e "${GREEN}✅ 部署报告已生成: $REPORT_FILE${NC}"

# 显示部署完成信息
echo ""
echo -e "${GREEN}🎉 部署准备完成！${NC}"
echo ""
echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE}       部署摘要${NC}"
echo -e "${BLUE}========================================${NC}"
echo -e "${GREEN}客户端:${NC} $CLIENT_NAME"
echo -e "${GREEN}版本:${NC} $VERSION"
echo -e "${GREEN}模式:${NC} $DEPLOY_MODE"
echo -e "${GREEN}时间:${NC} $(date)"
echo ""
echo -e "${YELLOW}📁 生成的文件:${NC}"
echo "  • 版本信息: $VERSION_FILE"
echo "  • 构建脚本: $BUILD_SCRIPT"
echo "  • 哈希脚本: $HASH_SCRIPT"
echo "  • OSS脚本: $OSS_SCRIPT"
echo "  • 部署报告: $REPORT_FILE"
echo ""
echo -e "${YELLOW}🚀 后续步骤:${NC}"
echo "  1. 将应用文件放入 dist/$CLIENT_NAME/ 对应目录"
echo "  2. 运行构建: ./$BUILD_SCRIPT"
echo "  3. 计算哈希: ./$HASH_SCRIPT"
echo "  4. 上传OSS: ./$OSS_SCRIPT"
echo ""
echo -e "${YELLOW}🧪 测试命令:${NC}"
echo "  版本文件: curl $OSS_BASE_URL/updates/$CLIENT_DIR/version.json"
echo "  API测试: curl -X POST https://your-domain.com/api/client/version/check \\"
echo "           -H 'Content-Type: application/json' \\"
echo "           -d '{\"clientName\":\"$CLIENT_NAME\",\"currentVersion\":\"$VERSION\",\"platform\":\"windows\"}'"
echo ""
echo -e "${GREEN}✨ 部署脚本执行完成！${NC}"